package com.example.bank.service.impl;

import com.example.bank.entity.Account;
import com.example.bank.entity.Transaction;
import com.example.bank.repository.AccountRepository;
import com.example.bank.repository.TransactionRepository;
import com.example.bank.service.TransactionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.Optional;

@Service
public class TransactionServiceImpl implements TransactionService {
    
    @Autowired
    private TransactionRepository transactionRepository;
    
    @Autowired
    private AccountRepository accountRepository;
    
    @Override
    public Transaction createTransaction(Transaction transaction) {
        // 设置交易时间为当前时间
        if (transaction.getTransactionDate() == null) {
            transaction.setTransactionDate(LocalDateTime.now());
        }
        return transactionRepository.save(transaction);
    }
    
    @Override
    public Transaction getTransactionById(Long id) {
        return transactionRepository.findById(id).orElse(null);
    }
    
    @Override
    public List<Transaction> getAllTransactionsByAccountNumber(Long accountNumber) {
        return transactionRepository.findByAccount_number(accountNumber);
    }
    
    @Override
    public List<Transaction> getTransactionsByAccountNumberAndType(Long accountNumber, String type) {
        return transactionRepository.findByAccount_numberAndType(accountNumber, type);
    }
    
    @Override
    public List<Transaction> getTransactionsByAccountNumberAndDate(Long accountNumber, LocalDate date) {
        LocalDateTime startOfDay = date.atStartOfDay();
        LocalDateTime endOfDay = date.atTime(LocalTime.MAX);
        return transactionRepository.findByAccount_numberAndDateBetween(accountNumber, startOfDay, endOfDay);
    }
    
    @Override
    public List<Transaction> getTransactionsByPhoneNumberAndType(String phoneNumber, String type, LocalDate date) {
        // 根据手机号查找账户
        Optional<Account> accountOpt = accountRepository.findByPhone(phoneNumber);
        if (accountOpt.isEmpty()) {
            return List.of(); // 返回空列表
        }
        
        Long accountNumber = accountOpt.get().getAccount_number();
        LocalDateTime startOfDay = date.atStartOfDay();
        LocalDateTime endOfDay = date.atTime(LocalTime.MAX);
        
        return transactionRepository.findByAccount_numberAndTypeAndTransactionDateBetween(
                accountNumber, type, startOfDay, endOfDay);
    }
} 